package com.learn.io.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author wangxing
 * @version 2020/7/29 15:05 Administrator
 */
public class SocketServer {
    public static void main(String[] args) throws IOException {
//        建立服务端监听,指定监听端口
        ServerSocket serverSocket = new ServerSocket(9999);
        while(true){
            System.out.println("等待连接");
//            阻塞,等待连接出现
            Socket socket = serverSocket.accept();
            System.out.println("有客户端连接");
            new Thread(()->{
                try {
                    handler(socket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }

    }
    private  static void handler(Socket socket) throws IOException {
        System.out.println("thread id "+Thread.currentThread().getId());
        String message = "i read you message,you thread id is "+Thread.currentThread().getId();
        byte[]bytes = new byte[1024];
        System.out.println("ready read");
//        阻塞读取数据
        int read = socket.getInputStream().read(bytes);
        System.out.println("read end");
        if(read != 1){
            System.out.println("接收到客户端消息为:"+new String(bytes));
        }
        socket.getOutputStream().write(message.getBytes());
        socket.getOutputStream().flush();
    }
}
